package com.tanhua.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huanxin.HuanxinTemplate;
import com.tanhua.domain.Question;
import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.QuestionAPI;
import com.tanhua.dubbo.UserInfoAPI;
import com.tanhua.dubbo.mongo.RecommendUserAPI;
import com.tanhua.dubbo.mongo.UserLocationAPI;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.mongo.RecommendUser;
import com.tanhua.mongo.UserLocation;
import com.tanhua.vo.NearUserVo;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.RecommendUserVo;
import com.tanhua.vo.TodayBest;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserAPI recommendUserAPI;


    @DubboReference
    private UserInfoAPI userInfoAPI;

    @DubboReference
    private QuestionAPI questionAPI;

    @DubboReference
    private UserLocationAPI userLocationAPI;

    @Autowired
    private HuanxinTemplate template;


    public TodayBest todayBest() {
        //1 调用mongoDB查找出缘分值最高的那个UserId
        RecommendUser todayBestByMaxScore = recommendUserAPI.findTodayBestByMaxScore(UserHolder.getUserId());
        //如果是一个新注册的用户，这个用户是没有推荐列表的，此处就查不到
        //我们就随机一个值
        if (todayBestByMaxScore==null){
            todayBestByMaxScore = new RecommendUser();
            todayBestByMaxScore.setUserId(1L);
            todayBestByMaxScore.setScore(99d);
        }
        //2 根据userId去dubbo-db中查找出userinfo信息
        UserInfo userInfo = userInfoAPI.findById(todayBestByMaxScore.getUserId());
        //3 拼接返回结果
        TodayBest todayBest = new TodayBest();
        BeanUtils.copyProperties(userInfo,todayBest);
        todayBest.setId(Integer.valueOf(userInfo.getId().toString()));
        if (StringUtils.isNotBlank(userInfo.getTags())){
            todayBest.setTags(userInfo.getTags().split(","));
        }
        todayBest.setFateValue(todayBestByMaxScore.getScore().intValue());
        return todayBest;
    }

    public PageResult recommendation(RecommendUserVo recommendUserVo) {
        //1 根据当前登录用户的id去mongoDB中查找推荐列表
        Long userId = UserHolder.getUserId();
        List<RecommendUser> items= recommendUserAPI.queryRecommendUserList(userId);

        if (items==null||items.size()<=0){
            return null;
        }

        //2 根据推荐列表和条件去dubbo-db中查找userInfo信息

        //2.1 获取items的id集合
//        List<Long> idList = items.stream().map(item -> item.getUserId()).collect(Collectors.toList());
        List<Long> idList = new ArrayList<>();
        Map<Long, RecommendUser> recommendUserMap = new HashMap<>();
        //items.forEach(item -> idList.add(item.getUserId()));
        for (RecommendUser ru:items){
            idList.add(ru.getUserId());
            recommendUserMap.put(ru.getUserId(),ru);
        }
        //2.2 远程调用UserInfoApi
        Page page = userInfoAPI.findTuiJianLiebiao(idList,recommendUserVo);

        //3 拼接返回结果
        List<TodayBest> list = new ArrayList<>();
        List<UserInfo> records = page.getRecords();

        //items转成map集合,key:userId,值RecommendUser
//        Map<Long, RecommendUser> recommendUserMap = items.stream().collect(Collectors.toMap(RecommendUser::getUserId, Function.identity()));

        for (UserInfo userInfo : records){
            TodayBest todayBest = new TodayBest();
            BeanUtils.copyProperties(userInfo,todayBest);
            todayBest.setId(Integer.valueOf(userInfo.getId().toString()));
            if (StringUtils.isNotBlank(userInfo.getTags())){
                todayBest.setTags(userInfo.getTags().split(","));
            }

            todayBest.setFateValue(recommendUserMap.get(userInfo.getId()).getScore().intValue());
            list.add(todayBest);
        }
        Integer pages =  page.getRecords().size()%recommendUserVo.getPagesize()==0?
                page.getRecords().size()/recommendUserVo.getPagesize():
                (page.getRecords().size()/recommendUserVo.getPagesize()+1);
        return new PageResult(page.getRecords().size(),recommendUserVo.getPagesize(),pages,recommendUserVo.getPage(),list);
    }

    public TodayBest findPersonalInfo(Long userId) {
        //1 去mysql查找userInfo
        UserInfo userInfo = userInfoAPI.findById(userId);
        //2 去mongo查找fateValue
        RecommendUser ru  = recommendUserAPI.queryJiaRenFateValue(userId,UserHolder.getUserId());
        //3 封装结果
        TodayBest todayBest = new TodayBest();
        BeanUtils.copyProperties(userInfo,todayBest);
        if (StringUtils.isNotBlank(userInfo.getTags())){
            todayBest.setTags(userInfo.getTags().split(","));
        }
        todayBest.setFateValue(ru.getScore().intValue());
        return todayBest;
    }

    public Question strangerQuestions(Long userId) {

        Question question = questionAPI.findByUserId(userId);
        if (question==null){
            question=new Question();
            question.setTxt("你喜欢去看蔚蓝的大海还是去爬巍峨的高山？");
        }
        return question;
    }

    public void replyQuestions(Long toUserId, String reply) {
        //构造当前登录的消息-json字符串
        Long userId = UserHolder.getUserId();
        UserInfo userInfo = userInfoAPI.findById(userId);
        Map map = new HashMap<>();
        map.put("userId",userId);
        map.put("huanXinId","hx"+userId);
        map.put("nickname",userInfo.getNickname());
        map.put("strangerQuestion",strangerQuestions(toUserId).getTxt());
        map.put("reply",reply);

        String txt = JSON.toJSONString(map);
        System.out.println(txt);
        // 调用环信发送消息
        template.sendMsg("hx"+toUserId,txt);

    }

    public List<NearUserVo> nearSearch(String gender, String distance) {
        //1 mongdb中根据距离查找对应userId
        List<Long> userIdList = userLocationAPI.nearSearch(UserHolder.getUserId(),distance);
        if (userIdList!=null&&userIdList.size()>0){
            //2 去mysql中根据userIdList和性别，查找对应的数据
            List<UserInfo> userInfoList = userInfoAPI.findNearUserByGenderAndIdList(gender,userIdList);
            //3 封装
            List<NearUserVo> nearUserVoList = new ArrayList<>();
            userInfoList.forEach(ui ->{
                NearUserVo vo = new NearUserVo();
                vo.setUserId(ui.getId().intValue());
                vo.setAvatar(ui.getAvatar());
                vo.setNickname(ui.getNickname());
                nearUserVoList.add(vo);
            });
            //4 返回
            return nearUserVoList;
        }else {
            return null;
        }





    }
}
